<?php
/**
 * NfxRegionAgent.php
 *
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 山西牛酷信息科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.niushop.com.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */

namespace addons\Nsfx\data\service;

use addons\Nsfx\data\model\NfxPromoterRegionAgentApplyModel;
use addons\Nsfx\data\model\NfxPromoterRegionAgentApplyActionModel;
use addons\Nsfx\data\model\NfxPromoterModel;
use data\model\NsGoodsCategoryModel;

use data\model\NsOrderModel;
use data\service\Member\MemberAccount;
use data\service\Address;
use data\service\BaseService;

use think\Db;

/**
 * 区域分销申请服务层
 */
class NfxRegionAgentApply extends BaseService
{
    //操作
    private $action = [
        'apply' => [
            'title' => '提交申请',
            'res_status' => 'wait_audit',
        ],
        'edit_apply' => [
            'title' => '编辑申请',
            'res_status' => 'wait_audit',
        ],
        'check_pass' => [
            'title' => '审核通过',
            'res_status' => 'check_pass',
        ],
        'check_refuse' => [
            'title' => '审核拒绝',
            'res_status' => 'check_refuse',
        ],
        'confirm_pass' => [
            'title' => '确认通过',
            'res_status' => 'confirm_pass',
        ],
        'confirm_refuse' => [
            'title' => '确认驳回',
            'res_status' => 'confirm_refuse',
        ],
    ];

    //状态
    private $status = [
        'wait_audit' => [
            'name' => 'wait_audit',
            'title' => '待审核',
            'check_action' => [
                [
                    'name' => 'check_pass',
                    'title' => '审核通过',
                ],
                [
                    'name' => 'check_refuse',
                    'title' => '审核拒绝',
                ],
            ],
            'confirm_action' => [

            ],
        ],
        'check_pass' => [
            'name' => 'check_pass',
            'title' => '审核通过',
            'check_action' => [

            ],
            'confirm_action' => [
                [
                    'name' => 'confirm_pass',
                    'title' => '确认通过',
                ],
                [
                    'name' => 'confirm_refuse',
                    'title' => '确认驳回',
                ],
            ],
        ],
        'check_refuse' => [
            'name' => 'check_refuse',
            'title' => '审核拒绝',
            'check_action' => [

            ],
            'confirm_action' => [

            ],
        ],
        'confirm_pass' => [
            'name' => 'confirm_pass',
            'title' => '确认通过',
            'check_action' => [

            ],
            'confirm_action' => [

            ],
        ],
        'confirm_refuse' => [
            'name' => 'confirm_refuse',
            'title' => '确认驳回',
            'check_action' => [
                [
                    'name' => 'check_pass',
                    'title' => '审核通过',
                ],
                [
                    'name' => 'check_refuse',
                    'title' => '审核拒绝',
                ],
            ],
            'confirm_action' => [

            ],
        ],
    ];

    /**
     * 获取分类
     */
    public function getCategory($uid)
    {
        //获取所有一级分类
        $category_model = new NsGoodsCategoryModel();
        $category_list = $category_model->getQuery(['pid' => 0, 'is_visible' => 1], 'category_id,category_name,category_pic', 'sort asc');

        //获取已经申请过的品类
        $apply_model = new NfxPromoterRegionAgentApplyModel();
        $apply_list = $apply_model->getQuery(['uid' => $uid, 'audit_status' => 'confirm_pass'], 'category_ids', 'apply_id');
        $applied_category_id_arr = [];
        foreach($apply_list as $val){
            $category_id_arr = explode(',', $val['category_ids']);
            foreach($category_id_arr as $category_id){
                $applied_category_id_arr[$category_id] = $category_id;
            }
        }

        //做标记 判断是否已经申请过
        foreach($category_list as $key=>$val){
            if(in_array($val['category_id'], $applied_category_id_arr)){
                $category_list[$key]['is_applied'] = 1;
            }else{
                $category_list[$key]['is_applied'] = 0;
            }
        }

        return $category_list;
    }

    /**
     * 添加申请
     */
	public function addApply($data)
    {
        if(empty($data['uid']) || empty($data['province_id']) || empty($data['city_id']) || empty($data['district_id']) || empty($data['category_ids'])){
            return error([], ERROR, '参数缺失');
        }

        Db::startTrans();
        try{
            //检测
            $promoter_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();
            $apply_count = $promoter_region_agent_apply_model->getCount(['uid' => $data['uid'], 'audit_status' => ['neq', 'confirm_pass']]);
            if($apply_count > 0){
                Db::rollback();
                return error([], ERROR, '存在尚未通过审核的申请');
            }
            $apply_count = $promoter_region_agent_apply_model->getCount([
                'province_id' => $data['province_id'],
                'city_id' => $data['city_id'],
                'district_id' => $data['district_id'],
                'audit_status' => ['in', 'check_pass,confirm_pass']
            ]);
            if($apply_count > 0){
                Db::rollback();
                return error([], ERROR, '该地区已被申请');
            }

            $action_name = 'apply';

            //添加申请数据
            $promoter_model = new NfxPromoterModel();
            $promoter_info = $promoter_model->getInfo(['uid' => $data['uid']]);
            $apply_data = [
                'uid' => $data['uid'],
                'promoter_id' => $promoter_info['promoter_id'],
                'province_id' => $data['province_id'],
                'city_id' => $data['city_id'],
                'district_id' => $data['district_id'],
                'category_ids' => $data['category_ids'],
                'audit_status' => $this->action[$action_name]['res_status'],
                'apply_time' => time(),
                'action_time' => time(),
            ];


            $promoter_region_agent_apply_model->save($apply_data);
            $apply_id = $promoter_region_agent_apply_model->apply_id;

            //添加操作
            $this->addApplyAction($apply_id, $data['uid'], $action_name, '', []);

            Db::commit();
            return success(['apply_id' => $apply_id], SUCCESS, '申请成功');
        }catch(\Exception $e){
            Db::rollback();
            return error([], ERROR, $e->getMessage());
        }
    }

    /**
     * 编辑申请
     */
    public function editApply($data, $apply_id)
    {
        Db::startTrans();
        try{
            $action_name = 'edit_apply';

            //检测状态
            $promoter_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();
            $apply_info = $promoter_region_agent_apply_model->getInfo(['apply_id' =>  $apply_id], '*');
            if($apply_info['audit_status'] != 'check_refuse')
            {
                return AjaxReturn(-1, [], '申请状态不正确');
            }

            //修改申请数据
            $apply_data = [
                'province_id' => $data['province_id'],
                'city_id' => $data['city_id'],
                'district_id' => $data['district_id'],
                'category_ids' => $data['category_ids'],
                'audit_status' => $this->action[$action_name]['res_status'],
                'apply_time' => time(),
            ];

            $promoter_region_agent_apply_model->save($apply_data, ['apply_id' => $apply_id]);

            //添加操作
            $this->addApplyAction($apply_id, $apply_info['uid'], $action_name, '', []);

            Db::commit();
            return success(['apply_id' => $apply_id], SUCCESS, '申请修改成功');
        }catch(\Exception $e){
            Db::rollback();
            return error([], ERROR, $e->getMessage());
        }
    }

    /**
     * 获取申请信息
     */
    public function getApplyInfo($condition, $field = '*')
    {
        $promoter_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();
        $info = $promoter_region_agent_apply_model->getInfo($condition, $field);

        if(!empty($info)){
            //状态
            $audit_status = $this->status;
            $info['audit_status_name'] = $audit_status[$info['audit_status']];
            //分类
            $info['category_arr'] = $this->getApplyCategory($info['category_ids']);
            //地址
            $address_service = new Address();
            $info['address_arr'] = $address_service->getAddressArray($info['province_id'], $info['city_id'], $info['district_id']);
        }
        return $info;
    }

    /**
     * 获取申请分页列表
     */
    public function getApplyPageList($page_index = 1, $page_size = 0, $condition = [], $order = '')
    {
        $promoter_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();

        $alias = 'apply';
        $join = [
            ['sys_user user', 'apply.uid = user.uid', 'left'],
            ['nfx_promoter promoter', 'apply.uid = promoter.uid', 'left'],
        ];
        $field_arr = [
            "apply.*",
            "user.user_tel, user.nick_name, user.user_headimg",
            "promoter.is_region_agent",
        ];
        $field = join(',', $field_arr);
        $list = $promoter_region_agent_apply_model->pageQuery($page_index, $page_size, $condition, $order, $field, $alias, $join);

        $audit_status = $this->status;
        $address_service = new Address();
        foreach($list['data'] as $key=>$val){
            //状态
            $list['data'][$key]['audit_status_name'] = $audit_status[$val['audit_status']]['title'];
            //分类
            $list['data'][$key]['category_arr'] = $this->getApplyCategory($val['category_ids']);
            //地址
            $list['data'][$key]['address_arr'] = $address_service->getAddressArray($val['province_id'], $val['city_id'], $val['district_id']);
            //操作备注
            $last_action = $this->getLastAction($val['apply_id']);
            $list['data'][$key]['remark'] = $last_action['remark'];
        }
        return $list;
    }

    /**
     * 获取申请的分类数据
     */
    private function getApplyCategory($category_ids)
    {
        static $category_temp_list = [];
        if(empty($category_temp_list)){
            //获取所有一级分类
            $category_model = new NsGoodsCategoryModel();
            $category_list = $category_model->getQuery(['pid' => 0, 'is_visible' => 1], 'category_id,category_name,category_pic', 'sort asc');
            foreach($category_list as $key=>$val){
                $category_temp_list[$val['category_id']] = $val;
            }
        }

        $category_arr = [];
        $category_id_arr = explode(',', $category_ids);
        foreach($category_id_arr as $category_id){
            $category_arr[] = $category_temp_list[$category_id];
        }
        return $category_arr;
    }

    /**
     * 审核人通过
     */
    public function applyCheckPass($apply_id, $data)
    {
        Db::startTrans();
        try{
            $action_name = 'check_pass';

            //检测状态
            $promoter_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();
            $apply_info = $promoter_region_agent_apply_model->getInfo(['apply_id' => $apply_id], '*');
            if($apply_info['audit_status'] != 'wait_audit' && $apply_info['audit_status'] != 'confirm_refuse')
            {
                return error([], ERROR, '申请状态不正确');
            }

            $apply_count = $promoter_region_agent_apply_model->getCount([
                'province_id' => $apply_info['province_id'],
                'city_id' => $apply_info['city_id'],
                'district_id' => $apply_info['district_id'],
                'audit_status' => ['in', 'check_pass,confirm_pass']
            ]);
            if($apply_count > 0){
                Db::rollback();
                return error([], ERROR, '该地区已被申请');
            }

            //修改申请数据
            $apply_data = [
                'audit_status' => $this->action[$action_name]['res_status'],
                'action_time' => time(),
                'give_money' => $data['give_money'],
            ];
            $promoter_region_agent_apply_model->save($apply_data, ['apply_id' => $apply_id]);

            //添加操作
            $this->addApplyAction($apply_id, $data['action_uid'], $action_name, '', ['give_money' => $data['give_money']]);

            Db::commit();
            return success(['apply_id' => $apply_id], SUCCESS, '审核通过成功');
        }catch(\Exception $e){
            Db::rollback();
            return error([], ERROR, $e->getMessage());
        }
    }

    /**
     * 审核人拒绝
     */
    public function applyCheckRefuse($apply_id, $data)
    {
        Db::startTrans();
        try{
            $action_name = 'check_refuse';

            //检测状态
            $promoter_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();
            $apply_info = $promoter_region_agent_apply_model->getInfo(['apply_id' => $apply_id], '*');
            if($apply_info['audit_status'] != 'wait_audit' && $apply_info['audit_status'] != 'confirm_refuse')
            {
                return error([], ERROR, '申请状态不正确');
            }

            //修改申请数据
            $apply_data = [
                'audit_status' => $this->action[$action_name]['res_status'],
                'action_time' => time(),
            ];
            $promoter_region_agent_apply_model->save($apply_data, ['apply_id' => $apply_id]);

            //添加操作
            $this->addApplyAction($apply_id, $data['action_uid'], $action_name, $data['remark'], []);

            Db::commit();
            return success(['apply_id' => $apply_id], SUCCESS, '审核通过成功');
        }catch(\Exception $e){
            Db::rollback();
            return error([], ERROR, $e->getMessage());
        }
    }

    /**
     * 确认人通过
     */
    public function applyConfirmPass($apply_id, $data)
    {
        Db::startTrans();
        try{
            $action_name = 'confirm_pass';

            //检测状态
            $promoter_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();
            $apply_info = $promoter_region_agent_apply_model->getInfo(['apply_id' => $apply_id], '*');
            if($apply_info['audit_status'] != 'check_pass')
            {
                return error([], ERROR, '申请状态不正确');
            }

            //修改申请数据
            $apply_data = [
                'audit_status' => $this->action[$action_name]['res_status'],
                'action_time' => time(),
            ];
            $promoter_region_agent_apply_model->save($apply_data, ['apply_id' => $apply_id]);

            //修改推广员表状态
            $promoter_model = new NfxPromoterModel();
            $promoter_info = $promoter_model->getInfo(['uid' => $apply_info['uid']]);
            if($promoter_info['is_region_agent'] == 0){
                $promoter_model->save([
                    'is_region_agent' => 1,
                    'become_region_agent_time' => time(),
                    ], ['uid' => $apply_info['uid']]);
            }

            //发放赠送金额
            $member_account = new MemberAccount();
            $member_account->addMemberAccountData(0, 4, $apply_info['uid'], 1, $apply_info['give_money'], 21, $apply_id, '申请服务中心通过，平台赠送余额');

            //添加操作
            $this->addApplyAction($apply_id, $data['action_uid'], $action_name, '', []);

            Db::commit();
            return success(['apply_id' => $apply_id], SUCCESS, '确认成功');
        }catch(\Exception $e){
            Db::rollback();
            return error([], ERROR, $e->getMessage());
        }
    }

    /**
     * 确认人驳回
     */
    public function applyConfirmRefuse($apply_id, $data)
    {
        Db::startTrans();
        try{
            $action_name = 'confirm_refuse';

            //检测状态
            $promoter_region_agent_apply_model = new NfxPromoterRegionAgentApplyModel();
            $apply_info = $promoter_region_agent_apply_model->getInfo(['apply_id' => $apply_id], '*');
            if($apply_info['audit_status'] != 'check_pass')
            {
                return error([], ERROR, '申请状态不正确');
            }

            //修改申请数据
            $apply_data = [
                'audit_status' => $this->action[$action_name]['res_status'],
                'action_time' => time(),
            ];
            $promoter_region_agent_apply_model->save($apply_data, ['apply_id' => $apply_id]);

            //添加操作
            $this->addApplyAction($apply_id, $data['action_uid'], $action_name, $data['remark'], []);

            Db::commit();
            return success(['apply_id' => $apply_id], SUCCESS, '操作成功');
        }catch(\Exception $e){
            Db::rollback();
            return error([], ERROR, $e->getMessage());
        }
    }

    /**
     * 添加操作
     */
    private function addApplyAction($apply_id, $action_uid, $action_name, $remark = '', $other_info = [])
    {
        $action_model = new NfxPromoterRegionAgentApplyActionModel();
        $action_data = [
            'apply_id' => $apply_id,
            'action_uid' => $action_uid,
            'action_time' => time(),
            'action_name' => $action_name,
            'audit_status' => $this->action[$action_name]['res_status'],
            'remark' => $remark,
            'other_info' => json_encode($other_info),
        ];
        $res = $action_model->save($action_data);
        return $res;
    }

    /**
     * 获取操作列表
     */
    public function getApplyActionList($apply_id)
    {
        $action_model = new NfxPromoterRegionAgentApplyActionModel();
        $alias = 'action';
        $join = [
            ['sys_user user', 'action.action_uid = user.uid', 'left'],
        ];
        $field_arr = [
            "action.*",
            "user.user_name, user.nick_name",
        ];
        $list = $action_model
            ->where(['apply_id' => $apply_id])
            ->alias($alias)
            ->join($join)
            ->field(join(',', $field_arr))
            ->order('action_time asc')
            ->select();
        $action_arr = $this->action;
        foreach($list as $key=>$val){
            $list[$key]['other_info'] = json_decode($val['other_info'], true);
            $list[$key]['action_title'] = $action_arr[$val['action_name']]['title'];
        }
        return $list;
    }

    /**
     * 获取最后一个操作
     */
    public function getLastAction($apply_id)
    {
        $action_model = new NfxPromoterRegionAgentApplyActionModel();
        $info = $action_model->getFirstData(['apply_id' => $apply_id], 'action_time desc');
        return $info;
    }

    /**
     * 获取状态
     */
    public function getApplyStatus()
    {
        return $this->status;
    }

    /**
     * 获取服务中心已申请地址
     * @param $uid
     * @return array
     */
    public function getRegionAgentAddress($uid)
    {
        //获取所有已通过的申请
        $apply_model = new NfxPromoterRegionAgentApplyModel();
        $apply_list = $apply_model->getQuery(['uid' => $uid, 'audit_status' => 'confirm_pass'], '*', 'apply_id asc');
        $address_list = [];

        foreach($apply_list as $key=>$val){
            $address_list[$val['district_id']] = [
                'province_id' => $val['province_id'],
                'city_id' => $val['city_id'],
                'district_id' => $val['district_id'],
            ];
        }

        $address_service = new Address();
        foreach($address_list as $key=>$val){
            $address_list[$key]['address_info'] = $address_service->getAddress($val['province_id'], $val['city_id'], $val['district_id']);
        }
        return $address_list;
    }

    /**
     * 检测订单地址与服务中心是否相同
     * @param $order_id
     * @param $region_agent_uid
     */
    public function checkOrderAddress($order_info)
    {
        $check_res = false;

        $apply_model = new NfxPromoterRegionAgentApplyModel();
        $promoter_model = new NfxPromoterModel();

        $buyer_id = $order_info['buyer_id'];
        $promoter_info = $promoter_model->getInfo(['uid' => $buyer_id]);
        if($promoter_info['parent_promoter'] != 0 && $promoter_info['is_region_agent'] = 1){
            $agent_promoter_id = $promoter_info['parent_promoter'];
            $receiver_province = $order_info["receiver_province"];
            $receiver_city = $order_info["receiver_city"];
            $receiver_district = $order_info["receiver_district"];
            $apply_count = $apply_model->getCount([
                'promoter_id' => $agent_promoter_id,
                'province_id' => $receiver_province,
                'city_id' => $receiver_city,
                'district_id' => $receiver_district,
                'audit_status' => 'confirm_pass',
            ]);
            if($apply_count > 0){
                $check_res = true;
            }
        }

        return $check_res;
    }
}